<?php 

function parse_msg($usr_msg) {
$types = array(
0 => array(0 => "indian", 1 =>"wheat indian"),
1 => array(0 => "mexican", 1 =>"wheat mexican"),
2 => array(0 => "peas", 1 => "peas"),
3 => array(0 => "sunflower", 1 =>"seed sunflower"),
4 => array(0 =>"bengal",1 =>"gram bengal"),
5 => array(0 =>"dark", 1 => "gram dark"),
6 => array(0 =>"chilli", 1 =>"chilli"),
7 => array(0 =>"rice", 1 =>"rice"),
8 => array(0 =>"jaggery", 1 =>"jaggery"),
9 => array(0 =>"sugar", 1 =>"sugar"),
10 => array(0 =>"mustard", 1 =>"seed mustard"),
11 => array(0 =>"corn" ,1 =>"corn"),
12 => array(0 =>"paddy",1 =>"paddy"),
13 => array(0 =>"cotton", 1 =>"seed cotton")
);

$querypair = array(0 => false, 1 => false);
$commands = array(0 =>"latest", 1 => "high", 2=> "low", 3 => "avg", 4 => "total");

foreach($types as $grain){
	foreach($usr_msg as $token){
		if(strtolower($token)==$grain[0]){
			$querypair[0] = $grain[1];
			break 2;
			}
		}
	}

foreach($commands as $command){	
	foreach($usr_msg as $token){
		if(strtolower($token)==$command){
			$querypair[1] = $command;
			break 2;
			}
		}
	}
	
return $querypair;
}


function fix_grain($toFix) {
	$toFix = explode(" ", $toFix);
	if(count($toFix) > 1){
		$temp = $toFix[0];
		$toFix[0] = $toFix[1];
		$toFix[1] = $temp;
		}
	return implode(" ", $toFix);
	}

$msg = trim(urldecode($_POST['body'])); 
$usr_query = parse_msg(explode(" ", $msg));

/*
$msg = explode(' ', $msg);
$msg[0] = '';
$msg = implode(' ', $msg);
$msg = trim($msg);  

//strtok($msg, ": ");
$grain = strtok($msg, ": ");
$command = strtok(": "); */
$db=new SQLiteDatabase("db/mandi");
$response = false;

if($usr_query[0]){
switch ($usr_query[1]){
	case "total":
	$result=$db->query("select sum(s.weight), avg(s.rate_per_quintal) from sale_table as s,product_table as p ".
					"where p.name_en = \"".$usr_query[0]."\" AND p.id = s.produce_id");
	if($result){
		$row=$result->fetch(SQLITE_ASSOC);
		$weightsum = $row['sum(s.weight)'];
		$avg_price = $row['avg(s.rate_per_quintal)']; 
		$weight_format = sprintf("%01.2f", $weightsum);
		$price_format = sprintf("%01.2f", $avg_price);
		$fixedgrain = fix_grain($usr_query[0]);
		$response = "Total ".$fixedgrain." sold was ".$weight_format." Quintals at ";
		$response .= "Rupees ".$price_format."/Quintal as of ";
		$response .= date("G:i j F Y");
		$response = utf8_encode($response);
	}
	break;
	
	case "latest": 
	$result=$db->query("select s.rate_per_quintal, s.sold_timestamp from sale_table as s,product_table as p ".
					"where p.name_en = \"".$usr_query[0]."\" AND p.id = s.produce_id ".
					 "order by s.sold_timestamp desc");
	if($result){
		$row=$result->fetch(SQLITE_ASSOC);
		$response = $row['s.rate_per_quintal']; 
		$formatted = sprintf("%01.2f", $response);
		$fixedgrain = fix_grain($usr_query[0]);
		$response = "Latest ".$fixedgrain." price was Rupees ".$formatted."/Quintal at ";
		$response .= date("G:i j F Y",$row['s.sold_timestamp']);
		$response = utf8_encode($response);
	}
	break;
	
	case "avg":
	case false:
	$result=$db->query("select avg(s.rate_per_quintal) from sale_table as s,product_table as p ".
					"where p.name_en = \"".$usr_query[0]."\" AND p.id = s.produce_id");
	if($result){
		$row=$result->fetch(SQLITE_ASSOC);
		$response = $row['avg(s.rate_per_quintal)']; 
		$formatted = sprintf("%01.2f", $response);
		$fixedgrain = fix_grain($usr_query[0]);
		$response = "Average ".$fixedgrain." price was Rupees ".$formatted."/Quintal at ";
		$response .= date("G:i j F Y");
		$response = utf8_encode($response);
	}
	break;
	
	case "high":
	$result=$db->query("select s.rate_per_quintal, s.sold_timestamp from sale_table as s,product_table as p ".
					"where p.name_en = \"".$usr_query[0]."\" AND p.id = s.produce_id ".
					 "order by s.rate_per_quintal desc");
	if($result){
		$row=$result->fetch(SQLITE_ASSOC);
		$response = $row['s.rate_per_quintal']; 
		$formatted = sprintf("%01.2f", $response);
		$fixedgrain = fix_grain($usr_query[0]);
		$response = "High ".$fixedgrain." price was Rupees ".$formatted."/Quintal at ";
		$response .= date("G:i j F Y", $row['s.sold_timestamp']);
		$response = utf8_encode($response);
	}
	break;
	
	case "low":
	$result=$db->query("select s.rate_per_quintal, s.sold_timestamp from sale_table as s,product_table as p ".
					"where p.name_en = \"".$usr_query[0]."\" AND p.id = s.produce_id ".
					 "order by s.rate_per_quintal asc");
	if($result){
		$row=$result->fetch(SQLITE_ASSOC);
		$response = $row['s.rate_per_quintal']; 
		$formatted = sprintf("%01.2f", $response);
		$fixedgrain = fix_grain($usr_query[0]);
		$response = "Low ".$fixedgrain." price was Rupees ".$formatted."/Quintal at ";
		$response .= date("G:i j F Y", $row['s.sold_timestamp']);
		$response = utf8_encode($response);
	}
	break;

}
}

if(!$response){
	$response = "To get price, SMS \"price <produce type> <recent, avg, high,low or total (Optional).";
	$response .= " Example: \"price peas recent\". For mandi capacity, SMS \"capacity\" ";
	$response = utf8_encode($response);
	//$response = utf8_encode($command);
	}
	
//$response = utf8_encode($msg);
$http_date = gmdate("D, d M Y H:i:s T"); 
//$response = $msg;
$n = strlen($response); 
header("Date: " . $http_date); 
header("Content-Type: text/plain"); 
header("Content-Length: " . $n); 
print $response; 
	

?>